package org.itzf.utils;

import java.util.Map;

public class ThreadLocalUtil {
    private static ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();

    public static <T> T get() {
        return (T) THREAD_LOCAL.get();
    }

    public static <T> void set(T value) {
        if (value instanceof Map) {
            THREAD_LOCAL.set((Map<String, Object>) value);
        } else {
            throw new IllegalArgumentException("ThreadLocalUtil 仅支持存储 Map<String, Object> 类型的数据");
        }
    }

    public static Integer getUserId() {
        Map<String, Object> map = get();
        if (map == null) {
            return null;
        }

        Object idObj = map.get("id");
        if (idObj instanceof Integer) {
            return (Integer) idObj;
        } else if (idObj instanceof Long) {
            return ((Long) idObj).intValue();
        } else if (idObj instanceof String) {
            try {
                return Integer.valueOf((String) idObj);
            } catch (NumberFormatException e) {
                System.out.println("ThreadLocal 中的 id 不是有效数字字符串: " + idObj);
                return null;
            }
        } else {
            System.out.println("ThreadLocal 中的 id 类型无法转换: " + (idObj != null ? idObj.getClass() : "null"));
            return null;
        }
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }
}